import { Byte } from '../../api/io/Byte';
import { HashMap } from '../../api/struct/HashMap';
import { Equip } from './Equip';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**装备管理属性枚举*/
export const enum E_EquipManagerSnapshot {
	/**已穿装备，特殊不一样*/
	WEAR_EQUIP = 0,
	/**枚举数量*/
	EnumCount = 1
}


/**装备管理*/
export class EquipManagerSnapshot {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_EQUIP_MANAGER_SNAPSHOT_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_EQUIP_MANAGER_SNAPSHOT_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: EquipManagerSnapshot[] = [];

	/**创建入口*/
	public static create(json?: string): EquipManagerSnapshot {
		const c = this.POOL.pop() || new EquipManagerSnapshot();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**已穿装备，特殊不一样*/
	protected _wearEquip: HashMap<number, Equip> = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (EquipManagerSnapshot.POOL.indexOf(this) === -1) {
			EquipManagerSnapshot.POOL.push(this);
		}
	}

	/**设置已穿装备，特殊不一样*/
	public putWearEquip(k: number, v: Equip): Equip {
		const ov = this._wearEquip.put(k, v);
		return ov;
	}


	/**获取已穿装备，特殊不一样*/
	public getWearEquip(k: number) {
		return this._wearEquip.get(k);
	}


	/**删除已穿装备，特殊不一样*/
	public removeWearEquip(k: number, autoDestroy = false): Equip {
		const ov = this._wearEquip.remove(k);
		if (autoDestroy && ov) {
			ov.destroy();
		}
		return ov;
	}


	/**获取已穿装备，特殊不一样映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getWearEquipKeys(): number[] {
		return this._wearEquip.getKeys();
	}


	/**获取已穿装备，特殊不一样映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getWearEquipValues(): Equip[] {
		return this._wearEquip.getValues();
	}


	/**清空已穿装备，特殊不一样映射表*/
	public clearWearEquipMap(autoDestroy = false): void {
		const ks = this._wearEquip.getKeys();
		for (let i = ks.length - 1; i >= 0; i--) {
			this.removeWearEquip(ks[i], autoDestroy);
		}
	}



	/**通过枚举获取值*/
	public getV(k: E_EquipManagerSnapshot): any {
		switch (k) {
			case E_EquipManagerSnapshot.WEAR_EQUIP: return this._wearEquip;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_EquipManagerSnapshot, v: any): void {
		switch (k) {
			case E_EquipManagerSnapshot.WEAR_EQUIP: this._wearEquip = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//已穿装备，特殊不一样
		if (this._wearEquip) {
			const list = this._wearEquip.getValues();
			for (let i = 0, len = list.length; i < len; i++) {
				list[i].destroy();
			}
			this._wearEquip.clear();
		}
		else {
			this._wearEquip = new HashMap<number, Equip>();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._wearEquip.size() > 0) {
			const ks = this._wearEquip.getKeys();
			const vs = this._wearEquip.getValues();
			const list: string[] = [];
			for (let i = 0, len = vs.length; i < len; i++) {
				list[i] = vs[i].stringify(false);
			}
			json.wearEquip = [ks, list];
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.wearEquip) {
			const ks: number[] = json.wearEquip[0] || (json.wearEquip.getKeys ? json.wearEquip.getKeys() : null);	//对象可能是json或者结构体
			const vs: string[] = json.wearEquip[1] || (json.wearEquip.getValues ? json.wearEquip.getValues() : null);
			if (ks && vs && ks.length === vs.length) {
				for (let i = 0, len = vs.length; i < len; i++) {
					this._wearEquip.put(ks[i], Equip.create(vs[i]));
				}
			}
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		//已穿装备，特殊不一样
		{
			const ks = this._wearEquip.getKeys();
			const vs = this._wearEquip.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint32(ks[i]);
				vs[i].toBytes(byte);
			}
		}
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		//已穿装备，特殊不一样
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint32();
				const v = Equip.create();
				v.fromBytes(byte);
				this._wearEquip.put(k, v);
			}
		}
		return this;
	}


	/**克隆*/
	public clone(): EquipManagerSnapshot {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = EquipManagerSnapshot.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = EquipManagerSnapshot.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];

			//已穿装备，特殊不一样
			if (idx === E_EquipManagerSnapshot.WEAR_EQUIP) {
				const k: number = us[i + 1];
				const ctrl: number = us[i + 2];
				if (ctrl === 0) {
					const oldv = this.removeWearEquip(k);
					if (oldv) {
						oldv.destroy()
					}
				}
				else if (ctrl === 1) {
					const newv = Equip.create(us[i + 3]);
					const oldv = this.putWearEquip(k, newv);
					if (oldv) {
						oldv.destroy()
					}
				}
				else {
					const curv = this.getWearEquip(k);
					if (curv) {
						curv.processUpdate(us[i + 3]);
					}
					else {
						console.error('EquipManagerSnapshot Equip is not exist when update! k = ' + k);
					}
				}
				IAsync.dispatch(eventID, idx, k, ctrl);
				i += ctrl === 0 ? 3 : 4;
				continue;
			}

			console.error('[Struct Data] can not find enum in EquipManagerSnapshot with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: EquipManagerSnapshot): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];


		//已穿装备，特殊不一样
		{
			const idx = E_EquipManagerSnapshot.WEAR_EQUIP;
			const ks1 = this._wearEquip.getKeys();
			const ks2 = other._wearEquip.getKeys();
			const rs = MathUtils.intersectSortedArray(ks1, ks2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getWearEquip(k);
					const oldv = other.getWearEquip(k);
					const ui = newv.getCompareInfo(oldv);
					if (ui && ui.length > 0) {
						updates.push(idx, k, 2, ui);
					}
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getWearEquip(k);
					updates.push(idx, k, 1, newv.stringify(false));
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(EquipManagerSnapshot.TOTAL_EVENT_ID, this.getV(0));
	}

}
